function getCookie(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : undefined;
}


$(function(){

    // 打开登录框
    $('.comment_form_logout').click(function () {
        $('.login_form_con').show();
    });

    // 收藏
    $(".collection").click(function () {
        // alert($(this).attr("data-newid"))
        var params = {
            "news_id":$(this).attr("data-newid"),
            "action":"collect"
        };
        $.ajax({
            url:"/news/news_collect",
            type:"post",
            data:JSON.stringify(params),
            headers:{
                "X-CSRFToken":getCookie("csrf_token")
            },
            contentType:"application/json",
            success:function (dat) {
                if(dat.errno == "0"){
                    $(".collection").hide();
                    // 显示取消收藏按钮
                    $(".collected").show();
                }else if (resp.errno == "4101"){
                    $('.login_form_con').show();
                }else{
                    alert(dat.errmsg)
                }
            }
        });
       
    });

    // 取消收藏
    $(".collected").click(function () {
        var params = {
            "news_id":$(this).attr("data-newid"),
            "action":"cancel_collect"
        };
        $.ajax({
            url:"/news/news_collect",
            type:"post",
            data:JSON.stringify(params),
            headers:{
                "X-CSRFToken":getCookie("csrf_token")
            },
            contentType:"application/json",
            success:function (dat) {
                if(dat.errno == "0"){
                    $(".collection").show();
                    // 显示取消收藏按钮
                    $(".collected").hide();
                }else if (resp.errno == "4101"){
                    $('.login_form_con').show();
                }else{
                    alert(dat.errmsg);
                }
            }
        })
     
    });

    
        // 评论提交
    $(".comment_form").submit(function (e) {
        e.preventDefault();
        // 获取提交数据
        var new_id = $(this).attr("data-newid");
        var comment_str = $(".comment_input").val();
        // 提交操作
        if(!comment_str){
            alert("请填写评论再提交")
        }

        var params = {
            "news_id":new_id,
            "comment":comment_str
        };
        // 提交ajax
        $.ajax({
            url:"/news/news_comment",
            type:"post",
            contentType:"application/json",
            headers:{
                "X-CSRFToken":getCookie("csrf_token")
            },
            data:JSON.stringify(params),
            success:function (resp) {
                var comment = resp.data;
                // alert(resp.errno)

                if (resp.errno == '0') {
                    // alert(resp.errno)
                    if(comment.user.avatar_url){
                        img_url = comment.user.avatar_url
                    }else {
                        img_url = "../../static/news/images/worm.jpg"
                    }
                    // 拼接内容
                    comment_html = '<div class="comment_list"  data-commentid="'+comment.id+'">'
                    comment_html += '<div class="person_pic fl">'
                    comment_html += '<img src="'+ img_url
                    comment_html += '" alt="用户图标">'
                    comment_html += '</div>'
                    comment_html += '<div class="user_name fl">'+comment.user.nick_name +'</div>'
                    comment_html += '<div class="comment_text fl">'
                    comment_html += comment.content
                    comment_html += '</div>'
                    comment_html += '<div class="comment_time fl">'+comment.create_time +'</div>'
                    comment_html += '<a href="javascript:;" class="comment_up has_comment_up fr">1</a>'
                    comment_html += '<a href="javascript:;" class="comment_reply fr">回复</a>'
                    comment_html += '<form class="reply_form fl">'
                    comment_html += '<textarea  class="reply_input"></textarea>'
                    comment_html += '<input type="submit" name="" value="回复" class="reply_sub fr">'
                    comment_html += '<input type="reset" name="" value="取消" class="reply_cancel fr">'
                    comment_html += '</form>'
                    comment_html += '</div>'
                    // 拼接到内容的前面
                    $(".comment_list_con").prepend(comment_html);
                    // 让comment_sub 失去焦点
                    $('.comment_sub').blur();
                    // 清空输入框内容
                    $(".comment_input").val("")
                }else {
                    alert(resp.errmsg)
                }
            }
        })

    });

    $('.comment_list_con').delegate('a,input','click',function(){

        var sHandler = $(this).prop('class');

        if(sHandler.indexOf('comment_reply')>=0)
        {
            $(this).next().toggle();

        }

        if(sHandler.indexOf('reply_cancel')>=0)
        {
            $(this).parent().toggle();

        }

        if(sHandler.indexOf('comment_up')>=0)
        {
            var $this = $(this);
            var comment_id = $(this).parent().attr("data-commentid");
            if(sHandler.indexOf('has_comment_up')>=0)
            {
                // 如果当前该评论已经是点赞状态，再次点击会进行到此代码块内，代表要取消点赞
                $this.removeClass('has_comment_up')
                // 取消点赞
                var params = {
                    "comment_id":comment_id,
                    "active":"concel_up"
                }
                $.ajax({
                    url:"/comment_up",
                    type:"post",
                    contentType:"application/json",
                    headers:{
                        "X-CSRFToken":getCookie("csrf_token")
                    },
                    data:JSON.stringify(params),
                    success:function (resp) {
                        // alert(resp.errno)
                        if(resp.errno == "0"){
                            // alert("ok")
                            $this.removeClass("has_comment_up");
                            $this.html(parseInt($this.html())-1);

                        }else{
                            alert(resp.errmsg)
                        }
                    }

                });

            }else {
                $this.addClass('has_comment_up')
                // 点赞
                var params = {
                    "comment_id":comment_id,
                    "active":"up"
                }
                $.ajax({
                    url:"/comment_up",
                    type:"post",
                    contentType:"application/json",
                    headers:{
                        "X-CSRFToken":getCookie("csrf_token")
                    },
                    data:JSON.stringify(params),
                    success:function (resp) {
                        // alert(resp.errno)
                        if(resp.errno == "0"){
                            // alert("ok")
                            $this.addClass("has_comment_up");
                            $this.html(parseInt($this.html())+1);

                        }else{
                            alert(resp.errmsg)
                        }
                    }

                });

            }
        }

        if(sHandler.indexOf('reply_sub')>=0)
        {
            // alert('回复评论')
            var news_id = $(this).parent().parent().parent().attr("data-newid");
            var parent_id = $(this).parent().parent().attr("data-commentid");
            var comment = $(this).prev(".reply_input").val();

            if (!comment) {
                alert('请输入评论内容')
                return
            }
            var params = {
                "news_id": news_id,
                "comment": comment,
                "parent_id": parent_id
            }
            $.ajax({
                url:"/news/news_comment",
                type:"post",
                contentType:"application/json",
                headers:{
                    "X-CSRFToken":getCookie("csrf_token")
                },
                data:JSON.stringify(params),
                success:function (resp) {
                    if (resp.errno == "0") {
                        var comment = resp.data
                        // 拼接内容
                        var comment_html = ""
                        comment_html += '<div class="reply_text_con fl" >'
                        comment_html += '<div class="user_name2">'+comment.user.nick_name+'</div>'
                        comment_html += '<div class="reply_text">'
                        comment_html += comment.content
                        comment_html += '</div>'
                        comment_html += '</div>'
                        $(".reply_coment").prepend(comment_html)
                        // 请空输入框
                        $this.prev().val('')
                        // 关闭
                        $this.parent().hide()
                    }else {
                        alert(resp.errmsg)
                    }
                }
            });
        }
    });

        // 关注当前新闻作者
    $(".focus").click(function () {
        var params = {
            "author_id":$(this).attr("data-userid"),
            "action":"followtion"
        };
        $.ajax({
            url:"/news/author_follow",
            type:"post",
            data:JSON.stringify(params),
            headers:{
                "X-CSRFToken":getCookie("csrf_token")
            },
            contentType:"application/json",
            success:function (dat) {
                if(dat.errno == "0"){
                    $(".focus").hide();
                    // 显示取消关注按钮
                    $(".focused").show();

                    $(".fans_num").html(parseInt($(".fans_num").html())+1);
                }else if (resp.errno == "4101"){
                    $('.login_form_con').show();
                }else{
                    alert(dat.errmsg)
                }
            }
        })

    });

    // 取消关注当前新闻作者
    $(".focused").click(function () {
        var params = {
            "author_id":$(this).attr("data-userid"),
            "action":"cancel_follow"
        };
        $.ajax({
            url:"/news/author_follow",
            type:"post",
            data:JSON.stringify(params),
            headers:{
                "X-CSRFToken":getCookie("csrf_token")
            },
            contentType:"application/json",
            success:function (dat) {
                if(dat.errno == "0"){
                    $(".focus").show();
                    // 显示关注按钮
                    $(".focused").hide();
                    $(".fans_num").html(parseInt($(".fans_num").html()) -1);
                }else if (resp.errno == "4101"){
                    $('.login_form_con').show();
                }else{
                    alert(dat.errmsg)
                }
            }
        });
    });
})